<template>
  <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :localeText="localeText1" @grid-ready="gridReady"
    style="height:calc(100% - 120px)" :rowData="dataList" :columnDefs="dataTClou">
  </AgGridVuesCopys>
  <paginationCopys :total="pages.total" v-model:current='pages.page' @change="pagingChange"
    @page-size-change="pagingSizeChange" :page-size="pages.size" />
  <a-modal popup-container="html" v-model:visible="visible" :mask-closable="false" :draggable="true" fullscreen>
    <template #title>
      <div style="width:100%;text-align:center;">{{ PaiModelYou?.workshop }}</div>
    </template>
    <template #footer>
      <a-space>
        <a-button @click="visible = false">关闭</a-button>
        <!-- <a-button>确认</a-button> -->
        <a-button type="primary" @click="insertAddOks">保存</a-button>
      </a-space>
    </template>
    <div>
      <table>
        <thead>
          <tr>
            <th class="th">排产卡号</th>
            <th class="th">{{ PaiModelYou?.flowCardCode }}</th>
            <th class="th">缸型</th>
            <th class="th">{{ PaiModelYou?.cylinderType }}</th>
            <th class="th">管型</th>
            <th class="th">{{ PaiModelYou?.castNum }}</th>
            <th class="th">匹数</th>
            <th class="th">{{ PaiModelYou?.houseNum }}</th>
            <th class="th">重量</th>
            <th class="th">{{ PaiModelYou?.flowCardWeight }}</th>
          </tr>
          <tr>
            <th colspan="10" class="th">机型推荐</th>
          </tr>
        </thead>
      </table>
      <AgGridVue :rowHeight="90" @grid-ready="TuiJianJt" style="height:580px" :headerHeight="30" :defaultColDef="{
        sortable: true,
        resizable: true,
      }" class='ag-theme-alpine' :rowData="jtdtBiao" :suppressMovableColumns="true"
        :columnDefs="setAggridMinwidths(TjCloumnDefs)" :localeText="localeText1" @FilterChanged="onFilterChangeds"
        @sortChanged="sortChanged">
      </AgGridVue>
      <table>
        <thead>
          <tr>
            <th class="th" colspan="11">流转卡工序时间计算</th>
          </tr>
          <tr>
            <th id="th" style="max-height:30px;word-wrap: break-word;" v-for="item in PaiModelYou?.useTime">
              {{ item.process }}
            </th>
          </tr>
          <tr>
            <th id="ths" v-for="item in PaiModelYou?.useTime">{{ item.time ? item.time : '123' }}</th>
          </tr>
        </thead>
      </table>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import {
  withDefaults,
  watch
} from 'vue'
import { post } from '@/api/http'
import { Message, Modal } from "@arco-design/web-vue"
import { AgGridVue } from 'ag-grid-vue3'
import emitter from "@/hooks/useEventBus"
import { localeText } from '@/api/aggridZw'
import setAggridMinwidths from '@/utils/setAggridMinWidth'

const localeText1: any = ref(localeText)

const props = withDefaults(
  defineProps<{
    form: any,
  }>(),
  {
    form: {},
  }
)

const pages = reactive({
  total: 0,
  page: 1,
  size: 10
})

const pagingChange = (val: any) => {
  pages.page = val
  selectAll(props.form)
}

const pagingSizeChange = (val: any) => {
  pages.size = val
  selectAll(props.form)
}

const gridReadys: any = ref()
const gridReady = (params: any) => {
  gridReadys.value = params.api
}

const dataList = ref([])

const dataTClou = ref([
  {
    headerName: '',//选择列头部显示的文字，可以为空
    checkboxSelection: true,//设置为ture显示为复选框
    headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
    pinned: 'left', //固定再左边
    width: 50 //列的宽度
  },
  { headerName: "订单类型", field: "orderNature", width: 150 },
  {
    headerName: "色样", field: "colorTry", width: 80, cellStyle: (val: any) => {
      return { backgroundColor: val.data['colorTry'] }
    }, cellRenderer: {
      template: `
        <div></div>`,
      setup(props: any) {
      },
    },
  },
  { headerName: "色称", field: "colorName", width: 150 },
  { headerName: "流转卡号", field: "flowCardCode", width: 150 },
  { headerName: "染整单号", field: "orderCode", width: 150 },
  { headerName: "客户交期", field: "lastDeliveryTime", width: 150 },
  { headerName: "色号", field: "colorCode", width: 150 },
  { headerName: "色称", field: "colorName", width: 150 },
  { headerName: "缸型", field: "cylinderType", width: 150 },
  { headerName: "管型", field: "castNum", width: 150 },
  { headerName: "匹数", field: "houseNum", width: 150 },
  { headerName: "重量(KG)", field: "flowCardWeight", width: 150 },
  { headerName: "车间", field: "workshop", width: 150 },
  { headerName: "颜色深浅", field: "colorDepth", width: 150 },
  {
    headerName: "工艺流程", children: [
      {
        headerName: "配坯", field: "配坯", width: 80, cellStyle: (val: any) => {
          if (val.data['配坯'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "缝头", field: "缝头", width: 80, cellStyle: (val: any) => {
          if (val.data['缝头'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "抓毛", field: "抓毛", width: 80, cellStyle: (val: any) => {
          if (val.data['抓毛'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "刷毛", field: "刷毛", width: 80, cellStyle: (val: any) => {
          if (val.data['刷毛'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "染布", field: "染布", width: 80, cellStyle: (val: any) => {
          if (val.data['染布'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "煮布", field: "煮布", width: 80, cellStyle: (val: any) => {
          if (val.data['煮布'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "水洗", field: "水洗", width: 80, cellStyle: (val: any) => {
          if (val.data['水洗'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "定型", field: "定型", width: 80, cellStyle: (val: any) => {
          if (val.data['定型'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "查布", field: "查布", width: 80, cellStyle: (val: any) => {
          if (val.data['查布'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      },
      {
        headerName: "包装", field: "包装", width: 80, cellStyle: (val: any) => {
          if (val.data['包装'] == 'Y') {
            return { backgroundColor: '#94d351' }
          } else {
            return { backgroundColor: '#d9d9d9' }
          }
        }
      }
    ]
  },
])

emitter.on('selectIndexOne', (val: any) => {
  pages.page = 1
  selectAll(val)
})

const selectAll = (val: any = {}) => {
  HttpPost({
    url: 'aps/schedulOrder/getPageInfo',
    data: {
      ...val,
      page: pages.page,
      size: pages.size,
      selectState: 0
    }
  }).then(({ code, data, message }) => {
    if (code == 200) {
      dataList.value = data.list
    } else {
      Message.error(message)
    }
  })
}

emitter.on('deletIndexOne', () => {
  if (gridReadys.value.getSelectedRows().length === 0) {
    return false
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      post({
        url: 'aps/schedulOrder/deleteInfo',
        data: gridReadys.value.getSelectedRows().map((o: any) => {
          return o.id
        }),
      }).then(({ code, data }: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
          pages.page = 1
          selectAll({})
        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
})

const PaiModelYou: any = ref()

let calCell = ''
let calCellval = ''

function JleteDelets(cal: any, cals: any) {
  calCell = cal
  calCellval = cals
}

function JleteDeletsDel() {
  calCell[calCellval] = ''
}

emitter.on('RPaiIndexOne', async () => {
  if (gridReadys.value.getSelectedRows().length == 0 && gridReadys.value.getSelectedRows().length == 1) {
    Message.error("请勾选需要排产的单号!")
    return
  }
  TuiJianJts.value.setColumnDefs([])
  const { data, code, message } = await HttpPost({
    url: '/aps/schedulOrder/getMachineInfo',
    data: gridReadys.value.getSelectedRows()[0]
  })
  if (code != 200) {
    Message.error(message)
    return
  }

  PaiModelYou.value = data
  TjCloumnDefs.value = data.machine.map((res: any) => {
    return {
      headerName: res.machineCode,
      field: res.machineCode,
      width: 100,
      cellStyle: (val: any) => {
        if (val.data[res.machineCode].split('\n')[1] == PaiModelYou.value?.flowCardCode) {
          return { backgroundColor: '#557ab4', border: '2px solid #000' }
        } else {
          return { backgroundColor: val.data[res.machineCode].split('\n')[4], border: '2px solid #000' }
        }
      },
      cellRenderer: {
        template: `
          <div style="width:100px;height:90px" class="newline-cell" draggable="true" @dragstart="onDragStart"
               @dragover="allowDrop" @drop="drop">{{ params.data[resCopy] ? "任务" + params.data[resCopy] : '' }}
          </div>`,
        setup(props: any) {
          const resCopy = ref(res.machineCode)
          const onDragStart = (event) => {
            setTimeout(() => {
              TuiJianJts.value.setRowData(jtdtBiao.value)
              TuiJianJts.value.ensureIndexVisible(props.params.rowIndex, 'middle')
            }, 0)
            let datas = JSON.parse(JSON.stringify(props.params.data[resCopy.value]))
            event.dataTransfer.setData('text/plain', props.params.data[resCopy.value])
            // setTimeout(() => {
            //     props.params.data[resCopy.value] = ''
            // }, 500)
            JleteDelets(props.params.data, resCopy.value)
          }
          const allowDrop = (event) => {
            event.preventDefault()
            console.log(event.y)
            if (event.y < 210) {
              setTimeout(() => {
                TuiJianJts.value.ensureIndexVisible(props.params.rowIndex, 'middle')
              }, 500)
            } else if (event.y > 650) {
              setTimeout(() => {
                TuiJianJts.value.ensureIndexVisible(props.params.rowIndex, 'middle')
              }, 500)
            }
            // TuiJianJts.value.ensureIndexVisible(props.params.rowIndex+3,'middle')
          }
          const drop = (event) => {
            if (!props.params.data[resCopy.value]) {
              event.preventDefault()
              let datass = event.dataTransfer.getData('text/plain')
              let dataList = datass.split('\n')
              dataList[0] = (props.params.rowIndex + 1)
              props.params.data[resCopy.value] = dataList.join('\n')
              setTimeout(() => {
                TuiJianJts.value.setRowData(jtdtBiao.value)
                TuiJianJts.value.ensureIndexVisible(props.params.rowIndex, 'middle')
              }, 0)
              JleteDeletsDel()
              // if (Object.values(jtdtBiao.value[jtdtBiao.value.length - 1]).some(val => val != '')) {
              //     let obj = {}
              //     data.machine.map(z => z.machineCode).forEach((res) => {
              //         obj[res] = ''
              //     })
              //     jtdtBiao.value.push(obj)
              // }
              jtdtBiao.value = jtdtBiao.value.filter((res, index) => {
                return Object.values(res).some(val => val != '')
              })
              let obj = {}
              data.machine.map(z => z.machineCode).forEach((res) => {
                obj[res] = ''
              })
              jtdtBiao.value.push(obj)
            }
          }
          return {
            drop,
            allowDrop,
            onDragStart,
            resCopy
          }
        },
      },
    }
  })
  let max = Math.max(...data.machine.map(res => res.cardSize))
  let BaseDataObj = []
  for (let i = 0; i < max + 1; i++) {
    let objs = {}
    for (let item of data.machine) {
      if (item.card[i]) {
        objs[item['machineCode']] = item.card[i].serialNum + '\n' + item.card[i].flowCardCode + '\n' + item.card[i].colorName + '\n' + item.card[i].houseNum + '\n' + item.card[i].colorTry
      }
      if (i == max) {
        objs[item['machineCode']] = ''
      }
    }
    BaseDataObj.push(objs)
  }
  console.log(BaseDataObj)
  jtdtBiao.value = BaseDataObj
  visible.value = true
})

const visible = ref(false)

const HttpPost = (UrlAndData: any = { url: '', data: '' }) => {
  return new Promise(async (r: any, j: any) => {
    r(await post(UrlAndData))
  })
}

const TuiJianJts = ref()

const TuiJianJt = (param: any) => {
  TuiJianJts.value = param.api
}

const onFilterChangeds = (params: any) => {
  let dataList: any = []

  params.api.forEachNodeAfterFilter((row: any, index: number) => {
    dataList.push(row.data)
  })

  params.api.forEachNode((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
  });

  let yourColumnDefs = TuiJianJts.value.getColumnDefs()
  // 找到行号列的配置对象
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  // 如果找到了行号列的配置对象，则更新其 headerValue 属性为最大的 ROW_INDEX
  if (rowIndexColumn) {
    rowIndexColumn.headerName = dataList.length;
    TuiJianJts.value.setColumnDefs(yourColumnDefs)
  }

}


const sortChanged = (params) => {
  let dataList = [];
  let maxRowIndex = 0;

  // 遍历过滤后的节点，更新行号并收集数据
  params.api.forEachNodeAfterFilter((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
    dataList.push(node.data);
    maxRowIndex = Math.max(maxRowIndex, rowIndex);
  });

  // 更新表头的最大行号
  let yourColumnDefs = TuiJianJts.value.getColumnDefs();
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  if (rowIndexColumn) {
    rowIndexColumn.headerName = maxRowIndex;
    TuiJianJts.value.setColumnDefs(yourColumnDefs);
  }
};


const jtdtBiao: any = ref([])
const TjCloumnDefs = ref([])
// watch(
//     () => jtdtBiao.value,
//     () => {
//         console.log(8888)
//         jtdtBiao.value.filter((res,index)=>{
//             if(index != jtdtBiao.value.length){
//                 return Object.values(res).some(val=>val!='')
//             }
//         })
//     },
//     { deep: true }
// )

const insertAddOks = () => {
  let addDatas = jtdtBiao.value.filter((res, index) => {
    return Object.values(res).some(val => val != '')
  })
  console.log(addDatas)
}
</script>
<style>
table {
  border-collapse: collapse;
  width: 100%;

}

.th {
  border: 1px solid black;
  text-align: center;
  padding: 8px;
}

#th {
  border: 1px solid black;
  text-align: center;
  max-width: 100px;
}

#ths {
  border: 1px solid black;
  text-align: center;
  max-width: 100px;
}

#th:not(:last-child):nth-child(-n+10) {
  background-color: #babfc7;
}

#th:last-child {
  background-color: #bcc589;
}

.newline-cell {
  white-space: pre-line;
  line-height: 20px;
  user-select: none;
}
</style>